using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using GameFrameWork;
using UnityEngine;

/// <summary>
/// 双发射手攻击策略 - 每次攻击发射两颗子弹，两颗子弹之间有短暂间隔
/// </summary>
public class RepeaterAttackStrategy : AttackStrategyBase
{
    private RepeaterSkillData m_RepeaterSkillData;
    private CancellationTokenSource m_CancellationTokenSource;

    public RepeaterAttackStrategy(SkillData data)
    {
        AttackData = data;
        if (data is RepeaterSkillData repeaterData)
        {
            m_RepeaterSkillData = repeaterData;
        }
    }

    public override void Execute(Entity target)
    {
        base.Execute(target);

        if (target == null)
        {
            Logger.LogWarning("RepeaterAttackStrategy", $"{Owner?.name} 攻击目标无效");
            return;
        }

        if (AttackData == null || AttackData.BulletData == null)
        {
            Logger.LogError("RepeaterAttackStrategy", $"{Owner?.name} 缺少子弹数据");
            return;
        }

        if (m_RepeaterSkillData == null)
        {
            Logger.LogError("RepeaterAttackStrategy", $"{Owner?.name} 技能数据不是 RepeaterSkillData 类型");
            return;
        }

        // 取消之前的发射任务（如果存在）
        Cancel();

        // 开始双发攻击
        StartDoubleFire(target).Forget();
    }

    /// <summary>
    /// 开始双发攻击
    /// </summary>
    private async UniTaskVoid StartDoubleFire(Entity target)
    {
        // 创建取消令牌
        m_CancellationTokenSource = new CancellationTokenSource();
        var token = m_CancellationTokenSource.Token;

        try
        {
            int bulletCount = m_RepeaterSkillData.BulletCount;
            float bulletInterval = m_RepeaterSkillData.BulletInterval;

            Logger.Log("RepeaterAttackStrategy", $"{Owner?.name} 开始双发攻击，共 {bulletCount} 发，间隔 {bulletInterval} 秒");

            // 连续发射
            for (int i = 0; i < bulletCount; i++)
            {
                // 检查是否被取消或植物已死亡
                if (token.IsCancellationRequested || !CheckCondition())
                {
                    Logger.Log("RepeaterAttackStrategy", $"{Owner?.name} 双发攻击被中断");
                    break;
                }

                // 检查目标是否仍然有效
                if (target == null || target.HealthComponent == null || target.HealthComponent.IsDead)
                {
                    Logger.Log("RepeaterAttackStrategy", $"{Owner?.name} 目标已失效，停止攻击");
                    break;
                }

                // 发射子弹
                FireSingleBullet(target);

                // 如果不是最后一发，等待间隔时间
                if (i < bulletCount - 1)
                {
                    await UniTask.Delay(TimeSpan.FromSeconds(bulletInterval), cancellationToken: token);
                }
            }

            Logger.Log("RepeaterAttackStrategy", $"{Owner?.name} 双发攻击完成");
        }
        catch (System.OperationCanceledException)
        {
            Logger.Log("RepeaterAttackStrategy", $"{Owner?.name} 双发攻击被取消");
        }
        finally
        {
            IsExecuting = false;
        }
    }

    /// <summary>
    /// 发射单发子弹
    /// </summary>
    private void FireSingleBullet(Entity target)
    {
        if (Owner == null || AttackData == null || AttackData.BulletData == null)
        {
            return;
        }

        var bulletData = AttackData.BulletData;
        var bullet = BulletPool.Instance.GetBullet(bulletData);

        if (bullet == null)
        {
            Logger.LogError("RepeaterAttackStrategy", $"无法获取子弹：{bulletData.BulletType}");
            return;
        }

        // 设置子弹位置
        Vector3 startPos = Owner.transform.position;
        if (bulletData.OffVec3 != Vector3.zero)
        {
            startPos += bulletData.OffVec3;
        }
        bullet.transform.position = startPos;

        // 创建移动策略
        var movement = MoveStrategyFactory.Create(bulletData.MoveData);
        bullet.Initialize(
            owner: Owner,
            movement: movement
        );
    }

    public override void Cancel()
    {
        base.Cancel();

        // 取消双发攻击任务
        if (m_CancellationTokenSource != null && !m_CancellationTokenSource.IsCancellationRequested)
        {
            m_CancellationTokenSource.Cancel();
            m_CancellationTokenSource.Dispose();
            m_CancellationTokenSource = null;
        }
    }

    public override bool CheckCondition()
    {
        return base.CheckCondition() &&
               AttackData != null &&
               AttackData.BulletData != null &&
               m_RepeaterSkillData != null;
    }
}

